﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace HY.Web
{
    public class JsonResultExtension : JsonResult
    {
        /// <summary>
        /// 格式化字符串
        /// </summary>
        public string FormatDateStr { get; set; } = "yyyy-MM-dd HH:mm:ss";


        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if ((this.JsonRequestBehavior == JsonRequestBehavior.DenyGet) && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            {
                throw new Exception("当前方法不允许GET请求");
            }

            HttpResponseBase response = context.HttpContext.Response;
            if (!string.IsNullOrEmpty(this.ContentType))
            {
                response.ContentType = this.ContentType;
            }
            else
            {
                response.ContentType = "application/json";
            }
            if (this.ContentEncoding != null)
            {
                response.ContentEncoding = this.ContentEncoding;
            }

            if (Data != null)
            {
                //使用Newtonsoft.Json序列化
                var timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };//这里使用自定义日期格式，默认是ISO8601格式        
                response.Write(JsonConvert.SerializeObject(Data, Formatting.Indented, timeConverter));

                //仍使用原始序列化器，然后通过正则替换日期字符串格式
                //原始序列化器，在序列化二维数组时，会把二维数组转换成一维数组
                //JavaScriptSerializer jss = new JavaScriptSerializer();
                //string jsonString = jss.Serialize(Data);
                //string p = @"\\/Date\((\d+)\)\\/";
                //MatchEvaluator matchEvaluator = new MatchEvaluator(this.ConvertJsonDateToDateString);
                //Regex reg = new Regex(p);
                //jsonString = reg.Replace(jsonString, matchEvaluator);
                //response.Write(jsonString);
            }
        }

        /// <summary>  
        /// 将Json序列化的时间由/Date(1294499956278)转为字符串 .
        /// </summary>  
        /// <param name="m">正则匹配</param>
        /// <returns>格式化后的字符串</returns>
        private string ConvertJsonDateToDateString(Match m)
        {
            string result = string.Empty;
            DateTime dt = new DateTime(1970, 1, 1);
            dt = dt.AddMilliseconds(long.Parse(m.Groups[1].Value));
            dt = dt.ToLocalTime();
            result = dt.ToString(FormatDateStr);
            return result;
        }
    }
}